<template>
  <div class="dictionary-manage">
    <el-card>
      <div class="header">
        <div class="header-left">
          <el-icon class="header-icon"><Collection /></el-icon>
          <span class="header-title">数据字典</span>
          <el-tag type="info" size="small">管理系统标准化数据</el-tag>
        </div>
                  <div class="header-actions">
            <el-button type="primary" @click="openCategoryDialog('add')">
              <el-icon><Plus /></el-icon>
              新增分类
            </el-button>
            <el-button @click="openItemDialog('add')" style="margin-left: 8px;">
              <el-icon><Plus /></el-icon>
              新增字典项
            </el-button>
          </div>
      </div>

      <!-- 分类管理区域 -->
      <div class="category-section">
        <div class="section-header">
          <h3>字典分类</h3>
          <el-button text @click="refreshCategories">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
        <div class="category-grid">
          <div
            v-for="category in categories"
            :key="category.id"
            class="category-card"
            :class="{ active: selectedCategory?.id === category.id }"
            @click="selectCategory(category)"
          >
            <div class="category-header">
              <div class="category-info">
                <h4>{{ category.name }}</h4>
                <p class="category-code">{{ category.code }}</p>
              </div>
              <div class="category-status">
                <el-tag :type="category.status === 'enabled' ? 'success' : 'info'" size="small">
                  {{ category.status === 'enabled' ? '启用' : '禁用' }}
                </el-tag>
              </div>
            </div>
            <p class="category-desc">{{ category.description }}</p>
            <div class="category-footer">
              <span class="item-count">{{ getCategoryItemCount(category.id) }} 项</span>
              <div class="category-actions">
                <el-button size="small" text @click.stop="editCategory(category)">
                  <el-icon><Edit /></el-icon>
                </el-button>
                <el-button size="small" text @click.stop="deleteCategory(category)" :disabled="getCategoryItemCount(category.id) > 0">
                  <el-icon><Delete /></el-icon>
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 字典项管理区域 -->
      <div class="item-section" v-if="selectedCategory">
        <div class="section-header">
          <h3>{{ selectedCategory.name }} - 字典项管理</h3>
          <div class="section-actions">
            <el-button @click="exportItems" :disabled="!filteredItems.length">
              <el-icon><Download /></el-icon>
              导出
            </el-button>
            <el-button @click="batchDelete" :disabled="!selectedItems.length" type="danger">
              <el-icon><Delete /></el-icon>
              批量删除
            </el-button>
          </div>
        </div>

        <!-- 过滤栏 -->
        <el-form :inline="true" :model="filter" class="filter-bar" label-width="80px">
          <el-form-item label="名称">
            <el-input v-model="filter.name" placeholder="字典项名称" clearable style="width: 150px;" />
          </el-form-item>
          <el-form-item label="编码">
            <el-input v-model="filter.code" placeholder="字典项编码" clearable style="width: 150px;" />
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="filter.status" clearable style="width: 120px;">
              <el-option label="启用" value="enabled" />
              <el-option label="禁用" value="disabled" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="doFilter">查询</el-button>
            <el-button @click="resetFilter">重置</el-button>
          </el-form-item>
        </el-form>

        <!-- 字典项表格 -->
        <el-table 
          :data="paginatedItems" 
          style="width: 100%" 
          @selection-change="handleSelectionChange"
          :default-sort="{prop: 'sort', order: 'ascending'}"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="name" label="名称" width="150" />
          <el-table-column prop="code" label="编码" width="120" />
          <el-table-column prop="value" label="值" width="120" />
          <el-table-column prop="label" label="标签" width="120" />
          <el-table-column prop="description" label="描述" min-width="200">
            <template #default="scope">
              <div class="desc-ellipsis">{{ scope.row.description }}</div>
            </template>
          </el-table-column>
          <el-table-column prop="sort" label="排序" width="80" />
          <el-table-column label="状态" width="100">
            <template #default="scope">
              <el-tag :type="scope.row.status === 'enabled' ? 'success' : 'info'">
                {{ scope.row.status === 'enabled' ? '启用' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="默认值" width="100">
            <template #default="scope">
              <el-tag v-if="scope.row.isDefault" type="warning" size="small">默认</el-tag>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="scope">
              <el-button size="small" @click="editItem(scope.row)">编辑</el-button>
              <el-button size="small" @click="toggleItemStatus(scope.row)">
                {{ scope.row.status === 'enabled' ? '禁用' : '启用' }}
              </el-button>
              <el-button size="small" type="danger" @click="deleteItem(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-pagination
          v-model:current-page="page.current"
          v-model:page-size="page.size"
          :total="page.total"
          layout="total, sizes, prev, pager, next, jumper"
          :page-sizes="[10, 20, 50]"
          style="margin-top: 16px; text-align: right;"
        />
      </div>

      <!-- 空状态 -->
      <div v-if="!selectedCategory" class="empty-state">
        <el-empty description="请选择一个字典分类开始管理">
          <el-button type="primary" @click="openCategoryDialog('add')">创建第一个分类</el-button>
        </el-empty>
      </div>
    </el-card>

    <!-- 分类管理弹窗 -->
    <el-dialog 
      v-model="categoryDialog.visible" 
      :title="categoryDialog.mode === 'add' ? '新增分类' : '编辑分类'" 
      width="500px" 
      :close-on-click-modal="false"
    >
      <el-form :model="categoryDialog.form" :rules="categoryRules" ref="categoryFormRef" label-width="100px">
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="categoryDialog.form.name" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="分类编码" prop="code">
          <el-input v-model="categoryDialog.form.code" placeholder="请输入分类编码（大写字母+下划线）" />
        </el-form-item>
        <el-form-item label="分类描述" prop="description">
          <el-input 
            v-model="categoryDialog.form.description" 
            type="textarea" 
            :rows="3"
            placeholder="请输入分类描述"
          />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="categoryDialog.form.sort" :min="1" :max="999" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="categoryDialog.form.status">
            <el-radio value="enabled">启用</el-radio>
            <el-radio value="disabled">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="categoryDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="saveCategory">保存</el-button>
      </template>
    </el-dialog>

    <!-- 字典项管理弹窗 -->
    <el-dialog 
      v-model="itemDialog.visible" 
      :title="itemDialog.mode === 'add' ? '新增字典项' : '编辑字典项'" 
      width="600px" 
      :close-on-click-modal="false"
    >
      <el-form :model="itemDialog.form" :rules="itemRules" ref="itemFormRef" label-width="100px">
        <el-form-item label="所属分类" prop="categoryId">
          <el-select v-model="itemDialog.form.categoryId" placeholder="请选择所属分类" style="width: 100%">
            <el-option 
              v-for="cat in categories" 
              :key="cat.id" 
              :label="cat.name" 
              :value="cat.id"
              :disabled="cat.status === 'disabled'"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="itemDialog.form.name" placeholder="请输入字典项名称" />
        </el-form-item>
        <el-form-item label="编码" prop="code">
          <el-input v-model="itemDialog.form.code" placeholder="请输入字典项编码（大写字母+下划线）" />
        </el-form-item>
        <el-form-item label="值" prop="value">
          <el-input v-model="itemDialog.form.value" placeholder="请输入字典项值" />
        </el-form-item>
        <el-form-item label="标签" prop="label">
          <el-input v-model="itemDialog.form.label" placeholder="请输入显示标签" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input 
            v-model="itemDialog.form.description" 
            type="textarea" 
            :rows="3"
            placeholder="请输入字典项描述"
          />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="itemDialog.form.sort" :min="1" :max="999" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="itemDialog.form.status">
            <el-radio value="enabled">启用</el-radio>
            <el-radio value="disabled">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="默认值" prop="isDefault">
          <el-checkbox v-model="itemDialog.form.isDefault">设为默认值</el-checkbox>
          <div class="form-tip">同一分类下只能有一个默认值</div>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input 
            v-model="itemDialog.form.remark" 
            type="textarea" 
            :rows="2"
            placeholder="请输入备注信息（可选）"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="itemDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="saveItem">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox, ElNotification } from 'element-plus'
import { 
  Collection, Plus, Edit, Delete, Refresh, Download 
} from '@element-plus/icons-vue'
import type { FormInstance, FormRules } from 'element-plus'
import type { 
  DictionaryCategory, 
  DictionaryItem, 
  DictionaryCategoryForm, 
  DictionaryItemForm,
  DictionaryFilter,
  DictionaryPage
} from '@/types/dictionary'
import dictionaryService from '@/services/dictionaryService'

// ==================== 响应式数据 ====================

// 分类数据
const categories = ref<DictionaryCategory[]>([])
const selectedCategory = ref<DictionaryCategory | null>(null)

// 字典项数据
const items = ref<DictionaryItem[]>([])
const selectedItems = ref<DictionaryItem[]>([])

// 分页数据
const page = reactive<DictionaryPage>({
  current: 1,
  size: 20,
  total: 0
})

// 过滤条件
const filter = reactive<DictionaryFilter>({
  categoryId: '',
  name: '',
  code: '',
  status: undefined
})

// 弹窗状态
const categoryDialog = reactive({
  visible: false,
  mode: 'add' as 'add' | 'edit',
  form: reactive<DictionaryCategoryForm>({
    name: '',
    code: '',
    description: '',
    sort: 1,
    status: 'enabled'
  }),
  editingId: ''
})

const itemDialog = reactive({
  visible: false,
  mode: 'add' as 'add' | 'edit',
  form: reactive<DictionaryItemForm>({
    categoryId: '',
    name: '',
    code: '',
    value: '',
    label: '',
    description: '',
    sort: 1,
    status: 'enabled',
    isDefault: false,
    remark: ''
  }),
  editingId: ''
})

// 表单引用
const categoryFormRef = ref<FormInstance>()
const itemFormRef = ref<FormInstance>()

// ==================== 计算属性 ====================

// 过滤后的字典项
const filteredItems = computed(() => {
  let result = [...items.value]
  
  if (filter.name) {
    result = result.filter(item => 
      item.name.toLowerCase().includes(filter.name!.toLowerCase())
    )
  }
  if (filter.code) {
    result = result.filter(item => 
      item.code.toLowerCase().includes(filter.code!.toLowerCase())
    )
  }
  if (filter.status) {
    result = result.filter(item => item.status === filter.status)
  }
  
  return result.sort((a, b) => a.sort - b.sort)
})

// 分页后的字典项
const paginatedItems = computed(() => {
  const start = (page.current - 1) * page.size
  const end = start + page.size
  return filteredItems.value.slice(start, end)
})

// ==================== 生命周期 ====================

onMounted(() => {
  loadCategories()
})

// 监听选中分类变化
watch(selectedCategory, (newCategory) => {
  if (newCategory) {
    filter.categoryId = newCategory.id
    loadItems()
    page.current = 1
  } else {
    items.value = []
    page.total = 0
  }
})

// ==================== 数据加载 ====================

// 加载分类数据
const loadCategories = () => {
  categories.value = dictionaryService.getCategories()
}

// 加载字典项数据
const loadItems = () => {
  if (selectedCategory.value) {
    items.value = dictionaryService.getItemsByCategory(selectedCategory.value.id)
    page.total = items.value.length
  }
}

// 刷新分类数据
const refreshCategories = () => {
  loadCategories()
  ElMessage.success('分类数据已刷新')
}



// ==================== 分类管理 ====================

// 选择分类
const selectCategory = (category: DictionaryCategory) => {
  selectedCategory.value = category
}

// 打开分类弹窗
const openCategoryDialog = (mode: 'add' | 'edit', category?: DictionaryCategory) => {
  categoryDialog.mode = mode
  categoryDialog.visible = true
  
  if (mode === 'edit' && category) {
    categoryDialog.editingId = category.id
    Object.assign(categoryDialog.form, {
      name: category.name,
      code: category.code,
      description: category.description,
      sort: category.sort,
      status: category.status
    })
  } else {
    categoryDialog.editingId = ''
    Object.assign(categoryDialog.form, {
      name: '',
      code: '',
      description: '',
      sort: 1,
      status: 'enabled'
    })
  }
}

// 编辑分类
const editCategory = (category: DictionaryCategory) => {
  openCategoryDialog('edit', category)
}

// 删除分类
const deleteCategory = async (category: DictionaryCategory) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除分类"${category.name}"吗？删除后无法恢复。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    dictionaryService.deleteCategory(category.id)
    loadCategories()
    
    if (selectedCategory.value?.id === category.id) {
      selectedCategory.value = null
    }
    
    ElMessage.success('分类删除成功')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败：该分类下存在字典项')
    }
  }
}

// 保存分类
const saveCategory = async () => {
  if (!categoryFormRef.value) return
  
  try {
    await categoryFormRef.value.validate()
    
    if (categoryDialog.mode === 'add') {
      dictionaryService.addCategory(categoryDialog.form)
      ElMessage.success('分类创建成功')
    } else {
      dictionaryService.updateCategory(categoryDialog.editingId, categoryDialog.form)
      ElMessage.success('分类更新成功')
    }
    
    categoryDialog.visible = false
    loadCategories()
  } catch (error) {
    console.error('保存分类失败:', error)
  }
}

// ==================== 字典项管理 ====================

// 打开字典项弹窗
const openItemDialog = (mode: 'add' | 'edit', item?: DictionaryItem) => {
  itemDialog.mode = mode
  itemDialog.visible = true
  
  if (mode === 'edit' && item) {
    itemDialog.editingId = item.id
    Object.assign(itemDialog.form, {
      categoryId: item.categoryId,
      name: item.name,
      code: item.code,
      value: item.value,
      label: item.label,
      description: item.description,
      sort: item.sort,
      status: item.status,
      isDefault: item.isDefault,
      remark: item.remark || ''
    })
  } else {
    itemDialog.editingId = ''
    Object.assign(itemDialog.form, {
      categoryId: selectedCategory.value?.id || '',
      name: '',
      code: '',
      value: '',
      label: '',
      description: '',
      sort: 1,
      status: 'enabled',
      isDefault: false,
      remark: ''
    })
  }
}

// 编辑字典项
const editItem = (item: DictionaryItem) => {
  openItemDialog('edit', item)
}

// 删除字典项
const deleteItem = async (item: DictionaryItem) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除字典项"${item.name}"吗？删除后无法恢复。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    dictionaryService.deleteItem(item.id)
    loadItems()
    ElMessage.success('字典项删除成功')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 批量删除
const batchDelete = async () => {
  if (selectedItems.value.length === 0) return
  
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedItems.value.length} 个字典项吗？删除后无法恢复。`,
      '确认批量删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const ids = selectedItems.value.map(item => item.id)
    dictionaryService.deleteItems(ids)
    loadItems()
    selectedItems.value = []
    ElMessage.success('批量删除成功')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量删除失败')
    }
  }
}

// 切换字典项状态
const toggleItemStatus = (item: DictionaryItem) => {
  const newStatus = item.status === 'enabled' ? 'disabled' : 'enabled'
  dictionaryService.updateItem(item.id, { status: newStatus })
  loadItems()
  ElMessage.success(`状态已${newStatus === 'enabled' ? '启用' : '禁用'}`)
}

// 保存字典项
const saveItem = async () => {
  if (!itemFormRef.value) return
  
  try {
    await itemFormRef.value.validate()
    
    if (itemDialog.mode === 'add') {
      dictionaryService.addItem(itemDialog.form)
      ElMessage.success('字典项创建成功')
    } else {
      dictionaryService.updateItem(itemDialog.editingId, itemDialog.form)
      ElMessage.success('字典项更新成功')
    }
    
    itemDialog.visible = false
    loadItems()
  } catch (error) {
    console.error('保存字典项失败:', error)
  }
}

// ==================== 过滤和分页 ====================

// 执行过滤
const doFilter = () => {
  page.current = 1
  loadItems()
}

// 重置过滤
const resetFilter = () => {
  Object.assign(filter, {
    name: '',
    code: '',
    status: undefined
  })
  page.current = 1
  loadItems()
}

// 处理选择变化
const handleSelectionChange = (selection: DictionaryItem[]) => {
  selectedItems.value = selection
}

// ==================== 工具方法 ====================

// 获取分类下的字典项数量
const getCategoryItemCount = (categoryId: string): number => {
  return items.value.filter(item => item.categoryId === categoryId).length
}

// 导出字典项
const exportItems = () => {
  // 这里可以实现导出功能
  ElNotification({
    title: '导出功能',
    message: '导出功能开发中...',
    type: 'info'
  })
}

// ==================== 表单验证规则 ====================

const categoryRules: FormRules = {
  name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入分类编码', trigger: 'blur' },
    { pattern: /^[A-Z_]+$/, message: '编码只能包含大写字母和下划线', trigger: 'blur' },
    { min: 2, max: 30, message: '长度在 2 到 30 个字符', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入分类描述', trigger: 'blur' },
    { max: 200, message: '描述不能超过 200 个字符', trigger: 'blur' }
  ],
  sort: [
    { required: true, message: '请输入排序值', trigger: 'blur' },
    { type: 'number', min: 1, max: 999, message: '排序值在 1 到 999 之间', trigger: 'blur' }
  ]
}

const itemRules: FormRules = {
  categoryId: [
    { required: true, message: '请选择所属分类', trigger: 'change' }
  ],
  name: [
    { required: true, message: '请输入字典项名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入字典项编码', trigger: 'blur' },
    { pattern: /^[A-Z_]+$/, message: '编码只能包含大写字母和下划线', trigger: 'blur' },
    { min: 2, max: 30, message: '长度在 2 到 30 个字符', trigger: 'blur' }
  ],
  value: [
    { required: true, message: '请输入字典项值', trigger: 'blur' },
    { max: 100, message: '值不能超过 100 个字符', trigger: 'blur' }
  ],
  label: [
    { required: true, message: '请输入显示标签', trigger: 'blur' },
    { max: 50, message: '标签不能超过 50 个字符', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入字典项描述', trigger: 'blur' },
    { max: 200, message: '描述不能超过 200 个字符', trigger: 'blur' }
  ],
  sort: [
    { required: true, message: '请输入排序值', trigger: 'blur' },
    { type: 'number', min: 1, max: 999, message: '排序值在 1 到 999 之间', trigger: 'blur' }
  ]
}
</script>

<style scoped>
.dictionary-manage {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.header-icon {
  font-size: 24px;
  color: var(--el-color-primary);
}

.header-title {
  font-size: 20px;
  font-weight: 600;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 8px;
}

/* 分类管理区域 */
.category-section {
  margin-bottom: 32px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.section-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.section-actions {
  display: flex;
  gap: 8px;
}

.category-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 16px;
}

.category-card {
  padding: 16px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  background: #fff;
}

.category-card:hover {
  border-color: var(--el-color-primary);
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.category-card.active {
  border-color: var(--el-color-primary);
  background: #f0f9ff;
}

.category-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 8px;
}

.category-info h4 {
  margin: 0 0 4px 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.category-code {
  margin: 0;
  font-size: 12px;
  color: #909399;
  font-family: 'Courier New', monospace;
}

.category-desc {
  margin: 0 0 12px 0;
  font-size: 14px;
  color: #606266;
  line-height: 1.4;
}

.category-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.item-count {
  font-size: 12px;
  color: #909399;
}

.category-actions {
  display: flex;
  gap: 4px;
}

/* 字典项管理区域 */
.item-section {
  margin-top: 24px;
  padding-top: 24px;
  border-top: 1px solid #f0f0f0;
}

.filter-bar {
  margin-bottom: 16px;
  padding: 16px;
  background: #fafafa;
  border-radius: 6px;
}

/* 表格样式 */
.desc-ellipsis {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  max-width: 200px;
}

/* 空状态 */
.empty-state {
  text-align: center;
  padding: 60px 20px;
}

/* 表单提示 */
.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
  line-height: 1.4;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }
  
  .header-actions {
    width: 100%;
    justify-content: flex-end;
  }
  
  .category-grid {
    grid-template-columns: 1fr;
  }
  
  .filter-bar {
    padding: 12px;
  }
}
</style>
